/*
 * ServicesApplication.java
 *
 * Created on April 22, 2007, 12:28 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.xeerkat.agent.apps;

import java.net.URI;
import java.util.Iterator;
import org.infoset.xml.Name;
import org.restlet.Application;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.data.MediaType;
import org.restlet.data.Protocol;
import org.restlet.data.Reference;
import org.restlet.data.Status;
import org.restlet.representation.StringRepresentation;
import org.restlet.routing.Router;
import org.xeerkat.agent.AgentContext;
import org.xeerkat.agent.services.Service;
import org.xeerkat.agent.services.ServiceMetadata;
import org.xeerkat.agent.services.ServiceRegistry;
import org.xeerkat.agent.services.ServiceRuntime;

/**
 *
 * @author alex
 */
@ServiceMetadata(id="http://www.xeerkat.org/Services/Services/2007/1/0",vendor="xeerkat.org",copyright="2008 xeerkat.org")
public class ServicesApplication extends Application 
{
   
   static Protocol XMPP = Protocol.valueOf("xeerkat");
   static URI NAMESPACE = URI.create("http://www.xeerkat.org/Vocabulary/Services/2007/1/0");
   AgentContext agentContext;
   /** Creates a new instance of ServicesApplication */
   public ServicesApplication(Context context)
   {
      agentContext = (AgentContext)context.getAttributes().get(AgentContext.AGENT_CONTEXT_ATTR);
   }
   
   public Restlet createRoot() {
      Router router = new Router();
      Restlet servicesApp = new Restlet() {
         public void handle(Request request, Response response) {
            response.setStatus(Status.SUCCESS_OK);
            StringBuilder builder = new StringBuilder();
            builder.append("<service-list xmlns='"+NAMESPACE+"'>\n");
            Iterator<ServiceRuntime> services = agentContext.getServices();
            while (services.hasNext()) {
               ServiceRuntime service = services.next();
               builder.append("<service interface='"+service.getMetadata()+"' vendor='"+service.getMetadata().vendor()+"' version='"+service.getMetadata().version()+"' copyright='"+service.getMetadata().copyright()+"' href='"+service.getPath()+"'/>\n");
            }
            builder.append("</service-list>");
            response.setEntity(new StringRepresentation(builder.toString(),MediaType.APPLICATION_XML));
         }
      };
      router.attach("/",servicesApp);
      router.attach("",servicesApp);
      return router;
   }
}
